package com.homer.gps.track.service;

import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.preference.PreferenceManager;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;

import com.homer.gps.track.R;
import com.homer.gps.track.Routes;
import com.homer.gps.track.RunningRoute;
import com.homer.gps.track.persist.DatabaseHelper;
import com.homer.gps.track.persist.PointModel;
import com.homer.gps.track.persist.Repository;
import com.homer.gps.track.persist.RouteModel;
import com.j256.ormlite.android.apptools.OpenHelperManager;

public class TrackService extends Service implements ITrackService, LocationListener {

	private boolean trackingEnabled = false;
	private MyBinder myBinder;
	private Handler trackHandler;
	private Runnable trackRunnable;
	private Repository repository;
	private DatabaseHelper dbHelper = null;
	private RouteModel actualRoute = null;
	private long startTime = 0;
	public static final String TAG = "com.homer.gps.track.service";

	private LocationManager locationManager;
	private WakeLock mWakeLock;
	private String provider;
	
	private double latitude;  
	private double longitude; 

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		
		PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
		mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
		mWakeLock.acquire();
		
		Log.i(TAG, "Received start id " + startId + ": " + intent);
		startInForeground();
		// We want this service to continue running until it is explicitly
		// stopped, so return sticky.
		return START_STICKY;
	}

	@Override
	public void onCreate() {
		super.onCreate();

		repository = new Repository(getHelper());
		myBinder = new MyBinder();
		trackHandler = new Handler();

		// Get the location manager
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 0, this);
		Criteria criteria = new Criteria();
		provider = locationManager.getBestProvider(criteria, false);
		Location location = locationManager.getLastKnownLocation(provider);

		// Initialize the location fields
		if (location != null) {
			Log.e(TAG, "Provider " + provider + " has been selected.");
			onLocationChanged(location);
		} else {

		}
	}

	@Override
	public IBinder onBind(Intent intent) {
		return myBinder;
	}

	public void toggleTracking(int routeId) {
		if (trackingEnabled) {
			Log.e(TAG, "Tracking stopped");
//			trackHandler.removeCallbacks(trackRunnable);
			trackingEnabled = false;
		}else {
			Log.e(TAG, "Tracking started");
//			startTime = System.currentTimeMillis();
			actualRoute = repository.getRouteForId(routeId);
			trackingEnabled = true;
			Location location = locationManager.getLastKnownLocation(provider);
			onLocationChanged(location);
//			trackRunnable = new Runnable() {
//
//				public void run() {
//					Location location = locationManager.getLastKnownLocation(provider);
//					locListener.onLocationChanged(location);
//					trackHandler.postDelayed(this, 2000);
//				}
//			};
//			trackHandler.postDelayed(trackRunnable, 2000);
		}
	}

	public boolean isTrackingEnabled(){
		return trackingEnabled;
	}

	private DatabaseHelper getHelper() {
		if (dbHelper == null) {
			dbHelper = (DatabaseHelper)OpenHelperManager.getHelper(this, DatabaseHelper.class);
		}
		return dbHelper;
	}

	public class MyBinder extends Binder {

		public ITrackService getService() {
			return TrackService.this;
		}

	}

	@Override
	public long getStartTime() {
		return startTime;
	}

	@Override
	public void onDestroy() {
		if (mWakeLock.isHeld())
		{
			mWakeLock.release();
		}
		super.onDestroy();
	}

	private void startInForeground()
	{
		NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.ic_launcher)
				.setContentTitle("my notific").setContentText("Hello World!").setOngoing(true);
		Intent onTheMoveIntent = null;
		if (trackingEnabled) {
			onTheMoveIntent = new Intent(this, RunningRoute.class);
			onTheMoveIntent.putExtra("createdRouteId", actualRoute.getId());
		}else {
			onTheMoveIntent = new Intent(this, Routes.class);
		}
		onTheMoveIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

		PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0,
				onTheMoveIntent, PendingIntent.FLAG_UPDATE_CURRENT);

		mBuilder.setContentIntent(resultPendingIntent);

		startForeground(10291, mBuilder.build());
	}

	@Override
	public void onLocationChanged(Location loc) {
		if (loc != null) {
			loc.getLatitude();  
			loc.getLongitude();  
			latitude=loc.getLatitude();  
			longitude=loc.getLongitude();  
			Log.e("latit:", String.valueOf(latitude));
			Log.e("longit:", String.valueOf(longitude));
			if (trackingEnabled && actualRoute != null) {
				PointModel point = new PointModel();
				point.setLatitude(latitude);
				point.setLongitude(longitude);
				point.setRoute(actualRoute);
				repository.saveOrUpdatePoint(point);
			}
			
			SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
			SharedPreferences.Editor editor = preferences.edit();
			editor.putString("Name","Harneet");
			editor.putFloat("lastspeed", loc.getSpeed());
			editor.commit();
		}
	}

	@Override
	public void onProviderDisabled(String provider) {
		Toast.makeText(TrackService.this, "Disabled provider " + provider,
				Toast.LENGTH_SHORT).show();
	}

	@Override
	public void onProviderEnabled(String provider) {
		Toast.makeText(TrackService.this, "Enabled new provider " + provider,
				Toast.LENGTH_SHORT).show();
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
		
	}
}
